#include "butils.h"

using namespace bhttp;

std::string butils::strip(const std::string& str)
{
    std::string nstr(str);
    if (!nstr.empty()) {
        nstr.erase(0, nstr.find_first_not_of(" \r\n\t"));
        nstr.erase(nstr.find_last_not_of(" \r\n\t") + 1);
    }
    return std::move(nstr);
}

bool butils::split(const std::string& str, const std::string& sep, std::string* pleft, std::string* pright)
{
    size_t pos = str.find(sep);
    if (pos != std::string::npos) {
        *pleft = strip(std::string(str, 0, pos));
        *pright = strip(std::string(str, pos + 1));
        return true;
    }
    else {
        *pleft = strip(str);
        *pright = std::string();
        return false;
    }
}

std::vector<std::string> butils::split(const std::string& src, const std::string& sep)
{
    std::string str(src);
    std::vector<std::string> des;
    auto pos = str.find(sep);
    while (pos != std::string::npos)
    {
        if (pos != 0) des.emplace_back(str.substr(0, pos));
        str.erase(0, pos + sep.size());
        pos = str.find(sep);
    }
    if (!str.empty())
    {
        des.emplace_back(str);
    }
    return des;
}
